package orange.com.openstack.sahara.api;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import net.minidev.json.JSONObject;
import orange.com.openstack.sahara.data.Plugin;
import orange.com.openstack.sahara.httpConnection.RestCall;

import com.google.gson.Gson;
import com.jayway.jsonpath.JsonPath;

/**
 * class allowing the interaction with the Plugins Rest service
 * 
 * @author osvaldo.cocucci@gmail.com
 * 
 */
public class Plugins {

	String endpoint;
	String tenantId;
	String token;
	Gson gson;

	/**
	 * @param endpoint
	 * @param tenantId
	 * @param token
	 * 
	 *            constructor
	 */
	public Plugins(String endpoint, String tenantId, String token) {
		gson = new Gson();
		this.endpoint = endpoint;
		this.tenantId = tenantId;
		this.token = token;
	}

	/**
	 * 
	 * This operation returns the list of all plugins.
	 */
	public List<Plugin> listPlugin() {
		List<Plugin> dataSources = new ArrayList<Plugin>();
		RestCall caller = new RestCall();
		HttpURLConnection connection = caller.connect(endpoint + tenantId
				+ "/plugins", null, "GET", token);
		try {
			if (connection.getResponseCode() != 200)
				return null;
			String JSONreponse = caller.getResponse(connection);
			connection.disconnect();
			List<JSONObject> dataSourcesJSON = JsonPath.read(JSONreponse,
					"$.plugins[*]");

			for (JSONObject json : dataSourcesJSON) {
				dataSources.add(gson.fromJson(json.toJSONString(),
						Plugin.class));
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataSources;
	}

	/**
	 * @param plugin_name
	 * 
	 *            This operation returns short plugin description.
	 */
	public Plugin showPlugin(String plugin_name) {
		RestCall caller = new RestCall();
		HttpURLConnection connection = caller.connect(endpoint + tenantId
				+ "/plugins/" + plugin_name, null, "GET", token);
		try {
			if (connection.getResponseCode() != 200)
				return null;
			String JSONreponse = caller.getResponse(connection);
			connection.disconnect();

			return gson.fromJson(((JSONObject) JsonPath.read(JSONreponse,
					"$.plugin")).toJSONString(), Plugin.class);

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


}
